package eventbus

import (
	"time"

	"file_explorer/common/log"
	"file_explorer/model"
)

const (
	EventKeyWidgetChecklistChange            = "widget_checklist_change"
	EventKeyWidgetTableOrderChange           = "widget_table_order_change"
	EventKeyWidgetTableExpandCellEntrySubmit = "widget_table_expand_cell_entry_submit"
	EventKeyGlobalConfUpdate                 = "global_conf_update"
	EventKeyOpListCtxChecklistChange         = "op_list_ctx_checklist_change"
	EventKeyOpListCtxFileChange              = "op_list_ctx_file_change"
	EventKeyRenameTabCtxResChange            = "rename_tab_ctx_res_change"
	EventKeyFileTabPathChange                = "file_tab_path_change"
	EventKeyAddTab                           = "add_tab"
	EventKeyRemoveTab                        = "remove_tab"
)

type EventBus struct {
	ConsumerMap map[string][]*model.EventConsumer
}

func (bus *EventBus) ProduceEvent(key string, msg map[string]interface{}) {
	log.Debug("new event, key=%v, msg=%v", key, msg)
	for _, consumer := range bus.ConsumerMap[key] {
		// 执行回调
		consumer.Callback(&model.Event{
			Key:        key,
			Msg:        msg,
			CreateTime: time.Now(),
		})
	}

}

func (bus *EventBus) RegisterConsumer(key string, callback func(event *model.Event)) {
	bus.ConsumerMap[key] = append(bus.ConsumerMap[key], &model.EventConsumer{
		Key:      key,
		Callback: callback,
	})
}

func GetEventMsg[R any](event *model.Event, key string) (r R) {
	if event.Msg == nil {
		return
	}
	if _, ok := event.Msg[key]; ok {
		r = event.Msg[key].(R)
	}
	return
}

func NewEventbus() *EventBus {
	return &EventBus{
		ConsumerMap: make(map[string][]*model.EventConsumer),
	}
}
